#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2020-01-19

@author: zhuyu
"""
import os
import time
import commands


# 大屏版本
BIG_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.iot.settings',
        'com.alipay.iot.master:monitor',
        'com.alipay.iot.master:worker',
        'com.alipay.iot.connect'
]

# 灵犀版本
START_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.mapp.content.display',
        'com.alipay.mapp.content.service',
        'com.alipay.iot.settings',
        'com.alipay.iot.master:monitor',
        'com.alipay.iot.master:worker'
]

RUN_APP_LIST = [
        'com.alipay.iot.master',
        'com.alipay.iot.ic',
        'com.alipay.iot.service',
        'com.alipay.iot.connect',
        'com.alipay.iot.osupdate',
        'com.alipay.iot.systemcommand',
        'com.alipay.iot.settings',
        'com.alipay.iot.xpaas',
        'com.alipay.iot.profile',
        'com.alipay.iot.merchantplugin',
]


def gettime():
    time.localtime(time.time())
    timestamp = time.strftime('%Y-%m-%d_%H:%M:%S', time.localtime(time.time()))
    return timestamp


def get_app_version():
    appinfo = {}
    lines = os.popen("adb shell pm list packages |grep alipay").readlines()
    for line in lines:
        version_value = ''
        packagename = line.replace('package:', '').strip(' ').strip('\n')
        versioninfos = os.popen("adb shell dumpsys package {}|grep versionName".format(packagename)).readlines()
        for version in versioninfos:
            if 'versionName' in version:
                version_value = version_value + version.replace('versionName=', '').strip('\n').strip(' ')
        appinfo[packagename] = version_value
    for package in appinfo:
        print package, ':', appinfo[package]

    print commands.getoutput('adb shell getprop |grep ro.alipayiot.build.version')


def kill_adb_server():
    os.popen("adb kill-server").readlines()


def kill_app(pid):
    os.popen("adb shell kill -9 {}".format(pid))
    time.sleep(4)


def rename_adbkey_rk3288():
    src_rk3288 = '/Users/wangjianwen/.android/adbkey.rk3288'
    src_ruyi = '/Users/wangjianwen/.android/adbkey.ruyi'
    dst = '/Users/wangjianwen/.android/adbkey'
    os.rename(dst, src_rk3288)
    os.rename(src_ruyi, dst)


def rename_adbkey_ruyi():
    src_rk3288 = '/Users/wangjianwen/.android/adbkey.rk3288'
    src_ruyi = '/Users/wangjianwen/.android/adbkey.ruyi'
    dst = '/Users/wangjianwen/.android/adbkey'

    os.rename(dst, src_ruyi)
    os.rename(src_rk3288, dst)


def adb_sec_test():
    kill_adb_server()
    dir_list = os.listdir('/Users/wangjianwen/.android')
    if 'adbkey' in dir_list and 'adbkey.rk3288' not in dir_list and 'adbkey.ruyi' in dir_list:
        rename_adbkey_rk3288()
    lines = os.popen("adb devices").readlines()
    time.sleep(3)
    print lines
    # 恢复adbkey
    kill_adb_server()
    dir_list = os.listdir('/Users/wangjianwen/.android')
    if 'adbkey' in dir_list and 'adbkey.rk3288' in dir_list and 'adbkey.ruyi' not in dir_list:
        rename_adbkey_ruyi()
    lines = os.popen("adb devices").readlines()
    time.sleep(3)
    print lines


def start_app():
    appinfo = []
    lines = os.popen("adb shell ps |grep alipay").readlines()
    for line in lines:
        appinfo.append(line.split(' ')[-1].strip('\n'))
    return appinfo


def get_app_info():
    appinfo = {}
    lines = os.popen("adb shell ps |grep alipay ").readlines()
    for line in lines:
        pro_info = line.split(' ')
        while '' in pro_info:
            pro_info.remove('')
        app_pid = pro_info[1]
        app_name = pro_info[-1].strip('\n')
        appinfo[app_pid] = app_name
    return appinfo


def get_app_pid(appname):
    lines = os.popen("adb shell ps |grep {} ".format(appname)).readlines()
    if len(lines) == 0:
        print 'get app pid fail {}'.format(appname)
        return
    for line in lines:
        pro_info = line.split(' ')
        while '' in pro_info:
            pro_info.remove('')
        app_pid = pro_info[1]
        appname_temp = pro_info[-1].strip('\n')
        if appname == appname_temp:
            return app_pid


def kill_antapp_test():
    os.popen("adb root")
    time.sleep(3)
    for appname in RUN_APP_LIST:
        pid1 = get_app_pid(appname)
        if pid1 is not None:
            # print '{} pid1->{}'.format(appname, pid1)
            kill_app(pid1)
        else:
            continue
        pid2 = get_app_pid(appname)
        if pid2 is not None and pid1 != pid2:
            # print 'pid2->{}'.format(pid2)
            print 'test app success {} pid is {}->{}'.format(appname, pid1, pid2)


def reboot_devices():
    num = 0
    i = 45
    while i:
        lines = os.popen("adb devices").readlines()
        # sn = '1912A68040100072'
        sn = 'MB01190703000213'
        for line in lines:
            if sn in line:
                num = num+1
                retime = time.strftime('%Y.%m.%d %H:%M:%S ', time.localtime(time.time()))
                start_list = start_app()
                diff_set = set(BIG_APP_LIST) - set(start_list)
                # diff_set = set(START_APP_LIST) - set(start_list)
                if len(diff_set) != 0:
                    print '开机启动app失败应用:{}'.format(','.join(diff_set))
                print '{} ---第{}次重启---'.format(retime, num)
                os.popen("adb reboot")
                time.sleep(70)
        i = i-1
        time.sleep(5)


def monitor_app_pid(num):
    # os.popen("adb root")
    time.sleep(3)
    pid_old = {}
    for appname0 in RUN_APP_LIST:
        pid_old[appname0] = get_app_pid(appname0)
        print '{} {} pid -->【{}】'.format(gettime(), appname0, pid_old[appname0])

    while num >= 0:
        time.sleep(10)
        for appname1 in RUN_APP_LIST:
            pid_new = get_app_pid(appname1)
            if pid_new != pid_old[appname1] and pid_new is not None:
                lines = os.popen("adb shell cat /proc/uptime").readlines()
                os_duration = lines[0].split(" ")[0]
                print '{} {} restart,{}->{},os duration {}'.format(gettime(), appname1, pid_old[appname1], pid_new, os_duration)
                pid_old[appname1] = pid_new
        if num % 30 == 0:
            print '剩余待执行次数 ---> {}'.format(num)
        num = num - 1


if __name__ == "__main__":
    # 获取版本信息
    get_app_version()
    # 进行adbkey的安全测试
    # for i in range(10):
    #     adb_sec_test()
    # 在userdebug版本下进行蚂蚁app的保活测试
    # for i in range(10):
    #     kill_antapp_test()
    #     time.sleep(5)
    #     print '\n===============================================\n'
    # 设备重启，并检查启动进程的测试
    # reboot_devices()
    # 监控蚂蚁app进程的pid变化
    # monitor_app_pid(100000)
    # get_meminfo()
